//
//  TabBarViewController.swift
//  weibo
//
//  Created by nick on 15/9/22.
//  Copyright © 2015年 cn.nick. All rights reserved.
//

import UIKit

class TabBarViewController: UITabBarController {
    // MARK: - 监听方法
    /// 点击撰写按钮的方法 - 是运行循环通过消息机制来调用方法
    /// 不能`单纯`的使用 private，一旦使用 private，运行循环无法找到方法，造成崩溃！
    /// 但是：Swift 中默认全局共享，不想共享的方法都建议使用 private
    /// 如果使用 @objc 修饰符号，在编译的时候，会对函数做特殊处理，保证运行循环能够通过消息机制
    /// 访问到此方法
    func clickAddEditButton () {
        print("发布微博按钮")
        let vc = ComposeViewController()
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 添加子控制器(方法重载)
        addChildViewController()
        
        setUpAddEditButton()
//        tabBar.bringSubviewToFront(addEditButton)
    }
    // 添加橙色按钮到最上层
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        tabBar.bringSubviewToFront(addEditButton)
    }
    
    func setUpAddEditButton () {
        // 添加按钮到tabbar上
        tabBar.addSubview(addEditButton)
        let count = self.childViewControllers.count
        let w = tabBar.frame.width / CGFloat(count) - 1
        addEditButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        addEditButton.addTarget(self, action: "clickAddEditButton", forControlEvents: UIControlEvents.TouchUpInside)
    }

    func addChildViewController() {
        
        addChildViewControllers(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewControllers(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(UIViewController())
        addChildViewControllers(MessageTableViewController(), title: "信息", imageName: "tabbar_message_center")
        addChildViewControllers(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    func addChildViewControllers(vc: UIViewController, title: String, imageName: String) {
        let nav = UINavigationController(rootViewController: vc)
//        vc.view.backgroundColor = UIColor.orangeColor()
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        tabBar.tintColor = UIColor.orangeColor()
        addChildViewController(nav)
    }
    
    // 懒加载按钮
    lazy var addEditButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", bgImageName: "tabbar_compose_button")
    
}
